package xw.qxypt.modules.baseinfo.service.impl;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xw.qxypt.common.utils.*;

import xw.qxypt.modules.baseinfo.dao.LhpDataWeatherStationDao;
import xw.qxypt.modules.baseinfo.entity.LhpDataRoadDetectorEntity;
import xw.qxypt.modules.baseinfo.entity.LhpDataVisibilityEntity;
import xw.qxypt.modules.baseinfo.entity.LhpDataWeatherStationEntity;
import xw.qxypt.modules.baseinfo.entity.LhpInstallationPointEntity;
import xw.qxypt.modules.baseinfo.service.LhpDataWeatherStationService;
import xw.qxypt.modules.baseinfo.service.LhpInstallationPointService;
import xw.qxypt.modules.sys.shiro.ShiroUtils;


@Service("lhpDataWeatherStationService")
public class LhpDataWeatherStationServiceImpl extends ServiceImpl<LhpDataWeatherStationDao, LhpDataWeatherStationEntity> implements LhpDataWeatherStationService {

    @Autowired
    private LhpInstallationPointService lhpInstallationPointService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String pointName = (String)params.get("pointName");
        String startTime = (String)params.get("startTime");
        if(!StringUtils.isNotBlank(startTime)){
            startTime = sdf.format(new Date())+" 00:00:00";
        }
        String endTime = (String)params.get("endTime");
        if(StringUtils.isNotBlank(endTime)){
            endTime = endTime+" 23:59:59";
        }
        List<LhpInstallationPointEntity> pointList = lhpInstallationPointService.getPointByUserId(ShiroUtils.getUserId());
        List<String> pIdList = new ArrayList<>();
        for(LhpInstallationPointEntity p:pointList){
            pIdList.add(p.getId());
        }
        if(pointName != null && !"".equals(pointName)){
            pIdList = new ArrayList<>();
            for(LhpInstallationPointEntity p:pointList){
                if(p.getPointName().indexOf(pointName) != -1){
                    pIdList.add(p.getId());
                }
            }
        }
        if(pIdList.size()==0){
            pIdList.add("safsedfgdgfdgfdg");
        }
        IPage<LhpDataWeatherStationEntity> page = this.page(
                new Query<LhpDataWeatherStationEntity>().getPage(params),
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .in(pIdList.size()>0,"point_id",pIdList)
                        .ge(StringUtils.isNotBlank(startTime),"data_time",startTime)
                        .le(StringUtils.isNotBlank(endTime),"data_time",endTime)
                        .orderByDesc("data_time")
        );
        List<LhpDataWeatherStationEntity> infoList = page.getRecords();
        for(LhpDataWeatherStationEntity ldws:infoList){
            for(LhpInstallationPointEntity lipe:pointList){
                if(ldws.getPointId().equals(lipe.getId())){
                    ldws.setPointName(lipe.getPointName());
                    break;
                }
            }
        }
        return new PageUtils(page);
    }

    @Override
    public List<LhpDataWeatherStationEntity> weatherStationOverlay() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -6);
        //根据用户id查询关联的安装点
        List<LhpInstallationPointEntity> pointList = lhpInstallationPointService.getPointByUserId(ShiroUtils.getUserId());
        List<String> pIdList = new ArrayList<>();
        for(LhpInstallationPointEntity p:pointList){
            pIdList.add(p.getId());
        }

        List<LhpDataWeatherStationEntity> weatherList=this.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .gt("data_time",c.getTime())
                        .in("point_id",pIdList)
        );
        return weatherList;
    }

    @Override
    public LhpDataWeatherStationEntity getDataWeatherStationByPointId(String pointId) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -15);
        LhpDataWeatherStationEntity dataWeatherStation=new LhpDataWeatherStationEntity();
        List<LhpDataWeatherStationEntity> weatherList=this.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .gt("data_time",c.getTime())
                        .in("point_id",pointId)
                        .orderByDesc("data_time")
        );

       /* //获取安装点坐标
        LhpInstallationPointEntity installationPoint=lhpInstallationPointService.getById(pointId);
        //通过接口获取天气信息
        String x=installationPoint.getXGaode();
        String y=installationPoint.getYGaode();
        double[] arr = MapGPSTranslateUtil.gcj02_To_Gps84(
                Double.parseDouble(y), Double.parseDouble(x));
        String xgps = arr[1] + "";
        String ygps = arr[0] + "";
        try {
            XinZhiUtil caiyun = new XinZhiUtil();
            String result1 = caiyun.getRealWeatherByLatitudeAndLongitude(xgps, ygps, null);
            JSONObject obj = JSONObject.fromObject(result1);

            String status = obj.get("status").toString();
            String skyConName="";
            String temperature="";
            String speed="";
            String humVal = "";
            if (status.equals("ok")) {
                JSONObject result = obj.getJSONObject("result");
                String resultStatus = result.get("status").toString();
                if (resultStatus.equals("ok")) {
                    DecimalFormat df = new DecimalFormat("0.0");
                    // 气温
                    temperature = df.format(Double.parseDouble(result.get("temperature").toString()));
                    // 天气状况
                    String skycon = result.get("skycon").toString();
                    String conArr1[] = WeatherTranslateUtil.getSkycon(skycon);
                    skyConName = conArr1[0];
                    // 风速 wind.speed
                    JSONObject wind = result.getJSONObject("wind");
                    String speed1 = wind.get("speed").toString();
                    speed = df.format(Double.parseDouble(speed1) / 3.6);
                    // 相对湿度
                    String humidity = result.get("humidity").toString();
                    if (!"".equals(humidity)) {

                        double v = Double.parseDouble(humidity) * 100;
                        humVal = df.format(v);
                    }
                }
            }*/
            if (weatherList.size()>0) {
                LhpDataWeatherStationEntity ldws =  weatherList.get(0);
                if("0".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("无降水");
                }else if("1".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("小雨");
                }else if("2".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("中雨");
                }else if("3".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("大雨");
                }else if("4".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("小雪");
                }else if("5".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("中雪");
                }else if("6".equals(ldws.getPrecipitationType())){
                    ldws.setPrecipitationType("大雪");
                }
                return ldws;
                //dataWeatherStation.setRealtime(skyConName);
                // dataWeatherStation.setSource("0");
            /*}else {
                //dataWeatherStation.setRealtime(skyConName);
               // dataWeatherStation.setSource("1");
               // dataWeatherStation.setAmbientTemp(temperature);
                dataWeatherStation.setWindSpeed(speed);
                dataWeatherStation.setRelativeHumidity(humVal);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
            }
        return null;
    }

    @Override
    public LhpDataWeatherStationEntity getDataWeatherStationByPointId1(String pointId) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -5);
        LhpDataWeatherStationEntity dataWeatherStation=new LhpDataWeatherStationEntity();
        List<LhpDataWeatherStationEntity> weatherList=this.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .gt("data_time",c.getTime())
                        .in("point_id",pointId)
        );
        if (weatherList.size()>0){
           return dataWeatherStation=weatherList.get(0);
        }
        return null;
    }

    @Override
    public List<LhpDataWeatherStationEntity> weatherStationChart(String pointId) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, -3);
        List<LhpDataWeatherStationEntity> weatherList=this.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .gt("data_time",c.getTime())
                        .eq("point_id",pointId)
                        .orderByAsc("data_time")
        );
        return weatherList;
    }

    @Override
    public Map weatherChart() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -10);
        //根据用户id查询关联的安装点
        List<LhpInstallationPointEntity> pointList = lhpInstallationPointService.getPointByUserId(ShiroUtils.getUserId());
        List<String> pIdList = new ArrayList<>();
        List<String> pNameList = new ArrayList<>();
        List<String> weatherTempList = new ArrayList<>();
        List<String> windSpeedList = new ArrayList<>();
        List<String> precipitationList = new ArrayList<>();
        Map<String,LhpDataWeatherStationEntity> map1 = new HashMap<>();
        Map<String,LhpInstallationPointEntity> map2 = new HashMap<>();
        for(LhpInstallationPointEntity p:pointList){
            pIdList.add(p.getId());
            map2.put(p.getId(), p);
        }
        List<LhpDataWeatherStationEntity> ldwsList=this.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .gt("data_time",c.getTime())
                        .in("point_id",pIdList)
        );
        LhpDataWeatherStationEntity minWeatherTemp = new LhpDataWeatherStationEntity();
        LhpDataWeatherStationEntity maxWindSpeed = new LhpDataWeatherStationEntity();
        LhpDataWeatherStationEntity maxPrecipitation = new LhpDataWeatherStationEntity();
        LhpDataWeatherStationEntity maxRelativeHumidity = new LhpDataWeatherStationEntity();
        if(ldwsList.size()>0){
            for (LhpDataWeatherStationEntity ldws : ldwsList) {
                map1.put(ldws.getPointId(), ldws);
            }
            for (String  s : pIdList) {
                if(map1.get(s) != null) {
                    weatherTempList.add(map1.get(s).getAirTemp());
                    windSpeedList.add(map1.get(s).getWindSpeed());
                    precipitationList.add(map1.get(s).getPrecipitation());
                    pNameList.add(map2.get(s).getPointName());
                }
            }
            //查询极值
            Collections.sort(ldwsList, new Comparator<LhpDataWeatherStationEntity>() {
                @Override
                public int compare(LhpDataWeatherStationEntity o1, LhpDataWeatherStationEntity o2) {
                    if(Double.parseDouble(o1.getAirTemp()) >= Double.parseDouble(o2.getAirTemp())) {
                        return 1;
                    }else {
                        return -1;
                    }
                }
            });
            minWeatherTemp = ldwsList.get(0);
            Collections.sort(ldwsList, new Comparator<LhpDataWeatherStationEntity>() {
                @Override
                public int compare(LhpDataWeatherStationEntity o1, LhpDataWeatherStationEntity o2) {
                    if(Double.parseDouble(o1.getWindSpeed()) >= Double.parseDouble(o2.getWindSpeed())) {
                        return -1;
                    }else {
                        return 1;
                    }
                }
            });
            maxWindSpeed = ldwsList.get(0);
            Collections.sort(ldwsList, new Comparator<LhpDataWeatherStationEntity>() {
                @Override
                public int compare(LhpDataWeatherStationEntity o1, LhpDataWeatherStationEntity o2) {
                    if(Double.parseDouble(o1.getPrecipitation()) >= Double.parseDouble(o2.getPrecipitation())) {
                        return -1;
                    }else {
                        return 1;
                    }
                }
            });
            maxPrecipitation = ldwsList.get(0);
            Collections.sort(ldwsList, new Comparator<LhpDataWeatherStationEntity>() {
                @Override
                public int compare(LhpDataWeatherStationEntity o1, LhpDataWeatherStationEntity o2) {
                    if(Double.parseDouble(o1.getRelativeHumidity()) >= Double.parseDouble(o2.getRelativeHumidity())) {
                        return -1;
                    }else {
                        return 1;
                    }
                }
            });
            maxRelativeHumidity = ldwsList.get(0);
        }
        Map map=new HashMap();
        map.put("maxRelativeHumidity",maxRelativeHumidity);
        map.put("maxPrecipitation",maxPrecipitation);
        map.put("maxWindSpeed",maxWindSpeed);
        map.put("minWeatherTemp",minWeatherTemp);
        map.put("pNameList",pNameList);
        map.put("weatherTempList",weatherTempList);
        map.put("windSpeedList",windSpeedList);
        map.put("precipitationList",precipitationList);
        return map;
    }

}
